package com.atguigu.day11;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.AggregateFunction;
import org.apache.flink.table.functions.TableAggregateFunction;
import org.apache.flink.util.Collector;

import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.api.Expressions.call;

public class Flink06_UDF_TableAggFun {
    public static void main(String[] args) {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        //2.从端口读取数据并转为WaterSensor
        SingleOutputStreamOperator<WaterSensor> waterSensrStream = env.socketTextStream("localhost", 9999)
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        String[] split = value.split(",");
                        return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
                    }
                });
        //3.获取表的执行环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        //流转表
        Table table = tableEnv.fromDataStream(waterSensrStream);

        //不注册直接使用
        //TableAPI
//        table
//                .groupBy($("id"))
//                .flatAggregate(call(MyUDTAF.class, $("vc")).as("value", "rank"))
////                .select($("id"),$("f0"),$("f1"))
//                .select($("id"),$("value"),$("rank"))
//                .execute()
//                .print();

        //先注册再使用 在sql中使用的话一定要先注册再使用
        tableEnv.createTemporarySystemFunction("top2Vc", MyUDTAF.class);
        table
                .groupBy($("id"))
                .flatAggregate(call("top2Vc", $("vc")))
                .select($("id"),$("f0"),$("f1"))
                .execute()
                .print();




    }

    public static class MyTopAcc{
        //第一名的水位
        public Integer firstVc;
        //第二名的水位
        public Integer secondVc;
    }

    //表聚合函数
   //求vc的top2
    public static class MyUDTAF extends TableAggregateFunction<Tuple2<Integer,String>,MyTopAcc>{

        @Override
        public MyTopAcc createAccumulator() {
            MyTopAcc myTopAcc = new MyTopAcc();
            myTopAcc.firstVc = Integer.MIN_VALUE;
            myTopAcc.secondVc = Integer.MIN_VALUE;
            return myTopAcc;
        }

        public void accumulate(MyTopAcc acc,Integer value){
            if (value>acc.firstVc){
                acc.secondVc = acc.firstVc;
                acc.firstVc = value;
            }else if (value>acc.secondVc){
                //证明不大于第一名但是大于第二名
                acc.secondVc = value;
            }
        }

        public void emitValue(MyTopAcc acc, Collector<Tuple2<Integer,String>> out){
            if (acc.firstVc!=Integer.MIN_VALUE){
                out.collect(Tuple2.of(acc.firstVc,"1"));
            }

            if (acc.secondVc!=Integer.MIN_VALUE){
                out.collect(Tuple2.of(acc.secondVc,"2"));
            }
        }
    }


}
